#encoding=utf8
'''
Created on 2012-9-15

@author: Geminiblue
'''
import os,sys,time

try:
	from twisted.internet import iocpreactor
	iocpreactor.install()
except:
	from twisted.internet import epollreactor
	epollreactor.install()

from twisted.internet import reactor
from twisted.internet.protocol import Protocol,Factory;
from twisted.protocols.basic import LineReceiver
from models import *;
from dispatch import *
from pub.Config import Config
from pub import Func,UserDict,RoomDict
from pub.LogInfo import LogInfo
from ConfigParser import ConfigParser
all_connections = []
user_list = {}
configFile = "config/appconfig.ini"
configObject = None
numRc = 1
cfg = ConfigParser()
cfg.read("config\config.ini")
class SequenceServer(LineReceiver):
    def __init__(self,):
        pass
    def connectionMade(self,):
        global numRc
        #1.接受对象
        #2.检查用户是否已存在
        #3.未连接创建用户对象，写入socket属性
        numRc = numRc+1
        print "connected %s"%(numRc)
        pass
           
        #self.transport.write(self.transport.client[0]);
    def connectionLost(self, reason):
        global numRc
        print "conncetion Losted"
        numRc = numRc-1
        print "lost %s"%(numRc)
       
        
        user=UserDict.getUserFromSocket(self);
        
        if user:            
            room=user.get_room();
            UserDict.deleteUserFromDict(user);
            if room:
                RoomDict.delUserToRoom(user, room.get_id());  
                if not room.get_user_list():
                	room.reset();      	
                else:              
                 	RoomDict.sendInfoToRoomAllUser(room,Config.EXIT_CMD,"退出房间");
            user=None;
            
            
            
        
        
    def lineReceived(self, data):
        #d = CommandParser("LOGIN#12#geminiblue#123456")     
        
        Func.debugInfo(data)
        if data!='':
            oCmd= CommandParser.CommandParser(self,data)
            sResult = str(oCmd.response())
            #self.transport.write(sResult)
        else:
            self.transport.write('Data Error')

class sqFactory(Factory):
    def __init__(self):
        pass
    def doStart(self, *args, **kwargs):
        return Factory.doStart(self, *args, **kwargs)
    def doStop(self, *args, **kwargs):
        return Factory.doStop(self, *args, **kwargs)
    def startFactory(self, ):
        '''
        服务初始化，加载配置文件
        '''
        
        try:            
            reload(sys)
            sys.setdefaultencoding('utf8');
            Config.cfg["DbConnectString"]={
                                                'user': cfg.get("Db","user"),
                                                'password': cfg.get("Db","password"),
                                                'host': cfg.get("Db","host"),
                                                'port': cfg.getint("Db","port"),
                                                'database': cfg.get("Db","daname"),
                                                'raise_on_warnings': cfg.getboolean("Db","raise_on_warnings"), }
            Config.B_SYS_DEBUG = cfg.getboolean("server","Debug")
            Config.B_SYS_TRACE = cfg.getboolean("server","TraceMessage")
            Config.I_MAX_DISTANCE = cfg.getint("server","MaxDistance")
            Config.D_USER_DICT={}
            self.initRoomDict(str(cfg.get("RoomInit","count")))
        except Exception,ex:
            LogInfo.writeLog("error", ex)
    def initRoomDict(self,sRoomCount):
        '''
        初始化房间字典
        '''
        Config.D_ROOM_DICT={}
        Condtion = " 1=1 "
        sOrderBy = " %s DESC" % Room.Room.COMMEND
        mRoom = RoomModel.RoomModel()
        results = mRoom.getRoomList(Condtion, sOrderBy,sRoomCount )       
        if(results!=None):
            for result in results:
                oRoom = Room.Room()
                oRoom.set_id(int(result[Room.Room.ROOMID]))
                oRoom.set_room_name(result[Room.Room.ROOMNAME])
                oRoom.set_introduce(result[Room.Room.INTRODUCE])
                oRoom.set_created(result[Room.Room.CREATED])
                oRoom.set_first_name(result[Room.Room.ROOMFIRSTNAME])
                oRoom.set_room_type(result[Room.Room.ROOMTYPE])
                oRoom.set_room_pri(result[Room.Room.ROOMPRI])
                oRoom.set_creator(result[Room.Room.CREATOR])
                oRoom.set_commend(result[Room.Room.COMMEND])
                oRoom.set_user_list([])
                oRoom.set_user_name_list({})
                RoomDict.addRoomToRoomDict(oRoom)
#                Config.addRoomToRoomDict(oRoom)
#                Func.addOrModUserToRoom(UserModel.UserModel().getUserInfoById(6), oRoom.get_id());
#                Func.addOrModUserToRoom(UserModel.UserModel().getUserInfoById(7), oRoom.get_id());
#                Func.addOrModUserToRoom(UserModel.UserModel().getUserInfoById(8), oRoom.get_id());
#                Func.addOrModUserToRoom(UserModel.UserModel().getUserInfoById(9), oRoom.get_id());
#                Func.addOrModUserToRoom(UserModel.UserModel().getUserInfoById(10), oRoom.get_id());
    def stopFactory(self):
        '''
        服务结束
        '''
        Func.debugInfo("factory Stotped")
if __name__ == '__main__':
    try:
 
	print "server started at %s"%Func.fNow()
        fc = sqFactory()
        fc.protocol = SequenceServer
        reactor.listenTCP(cfg.getint("server","GameServerPort"),fc)
	#print sys.modules['twisted.internet.reactor']
        reactor.run()
    except Exception,ex:
        Func.debugInfo(ex)